import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  message,
  Typography,
  Space,
  Select,
} from 'antd';
import {
  SendOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { sendMessage, getMessageDetail } from '../../api/message';
import { PrivateMessage } from '../../types';

const { Title } = Typography;
const { TextArea } = Input;

const ComposeMessage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [searchParams] = useSearchParams();
  const [originalMessage, setOriginalMessage] = useState<PrivateMessage | null>(null);
  const navigate = useNavigate();
  
  const replyId = searchParams.get('reply');

  useEffect(() => {
    if (replyId) {
      fetchOriginalMessage();
    }
  }, [replyId]);

  const fetchOriginalMessage = async () => {
    if (!replyId) return;
    
    try {
      const response = await getMessageDetail(Number(replyId));
      if (response.code === 200) {
        const msg = response.data;
        setOriginalMessage(msg);
        
        // 预填充回复信息
        form.setFieldsValue({
          receiverUsername: msg.senderUsername || msg.fromUsername,
          subject: msg.subject?.startsWith('Re:') ? msg.subject : `Re: ${msg.subject || msg.title}`,
        });
      }
    } catch (error) {
      console.error('获取原消息失败:', error);
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);
      const response = await sendMessage({
        receiverUsername: values.receiverUsername,
        subject: values.subject,
        content: values.content,
      });

      if (response.code === 200) {
        message.success('私信发送成功');
        navigate('/messages');
      } else {
        message.error(response.message || '发送失败');
      }
    } catch (error) {
      console.error('发送私信失败:', error);
      message.error('发送失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Card>
        <Title level={2}>
          <SendOutlined /> {replyId ? '回复私信' : '写私信'}
        </Title>

        {originalMessage && (
          <Card 
            size="small" 
            title="原消息" 
            style={{ marginBottom: 24, background: '#fafafa' }}
          >
            <p><strong>发件人:</strong> {originalMessage.senderUsername || originalMessage.fromUsername}</p>
            <p><strong>主题:</strong> {originalMessage.subject || originalMessage.title}</p>
            <p><strong>内容:</strong></p>
            <div style={{ 
              background: '#fff', 
              padding: 12, 
              borderRadius: 4,
              whiteSpace: 'pre-wrap' 
            }}>
              {originalMessage.content}
            </div>
          </Card>
        )}

        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="收件人"
            name="receiverUsername"
            rules={[
              { required: true, message: '请输入收件人用户名' },
              { min: 3, message: '用户名至少3个字符' }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入收件人用户名"
              disabled={!!replyId}
            />
          </Form.Item>

          <Form.Item
            label="主题"
            name="subject"
            rules={[
              { required: true, message: '请输入消息主题' },
              { min: 2, message: '主题至少2个字符' },
              { max: 100, message: '主题最多100个字符' }
            ]}
          >
            <Input
              placeholder="请输入消息主题"
              showCount
              maxLength={100}
            />
          </Form.Item>

          <Form.Item
            label="消息内容"
            name="content"
            rules={[
              { required: true, message: '请输入消息内容' },
              { min: 5, message: '消息内容至少5个字符' },
              { max: 2000, message: '消息内容最多2000个字符' }
            ]}
          >
            <TextArea
              rows={8}
              placeholder="请输入消息内容..."
              showCount
              maxLength={2000}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                icon={<SendOutlined />}
              >
                发送消息
              </Button>
              <Button onClick={() => navigate('/messages')}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default ComposeMessage; 